package com.css.dzj.dzjportal.modules.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.css.dzj.dzjportal.common.util.Constant;
import com.css.dzj.dzjportal.common.util.R;
import com.css.dzj.dzjportal.common.util.ServiceUtil;
import com.css.dzj.dzjportal.common.util.http.HttpClientUtil;
import com.css.dzj.dzjportal.modules.complaint.entity.JgWgrTsjbglEntity;
import com.css.dzj.dzjportal.modules.message.entity.PortalMsgEntity;
import com.css.dzj.dzjportal.modules.message.entity.QPortalMsgEntity;
import com.css.dzj.dzjportal.modules.message.mapper.MessageMapper;
import com.css.dzj.dzjportal.modules.message.service.MessageService;
import com.css.dzj.dzjportal.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 待办事项service实现类
 */
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    @Autowired
    private ServiceUtil serviceUtil;

    @Override
    public QueryResults<PortalMsgEntity> getPage(String complainTopic, Pageable pageable, HttpServletRequest request) {
        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";


        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
        }
        QPortalMsgEntity q = QPortalMsgEntity.portalMsgEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = (StringUtils.isEmpty(complainTopic)) ? predicate : ExpressionUtils.and(predicate, q.complainTopic.like("%" + complainTopic + "%"));
        predicate = (StringUtils.isEmpty(suserName)) ? predicate : ExpressionUtils.and(predicate, q.complainUser.like("%" + suserName + "%"));
        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));
        return jpaQueryFactory
                .selectFrom(q)
                .where(predicate)
                .orderBy(
                        // 根据创建日期，降序排序
                        q.createTime.desc()
                )
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
    }

    @Override
    @Transactional
    public String findByLinkId(String linkId,String id,String wgrRestUrl) {
        PortalMsgEntity portalMsgEntity = new PortalMsgEntity();
        portalMsgEntity = messageMapper.findById(id).get();
        //打开消息详情，默认已阅
        portalMsgEntity.setStatus(Constant.MSG_YY);
        update(portalMsgEntity);
        String url=wgrRestUrl+"/appeal/getOne";
        HashMap<String,String> map=new HashMap<>();
        map.put("id",linkId);
        String msg=HttpClientUtil.doGet(url,map);
        return msg;
    }

    @Override
    public PortalMsgEntity findById(String id) {
        return messageMapper.findById(id).get();
    }

    @Override
    public void update(PortalMsgEntity portalMsgEntity) {

    }

    @Override
    public void saveDB(PortalMsgEntity portalMsgEntity) {
        if (portalMsgEntity ==null){
            throw new RuntimeException("新增不能为空");
        }
        //新增消息，默认未阅
        portalMsgEntity.setStatus(Constant.MSG_WY);
        portalMsgEntity.setCreateTime(new Date());
        messageMapper.save(portalMsgEntity);
    }

    @Override
    public String getCountMsg(HttpServletRequest request) {
        /**
         * 获取suser
         */

        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";


        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            QPortalMsgEntity q = QPortalMsgEntity.portalMsgEntity;
            Predicate predicate = q.isNotNull().or(q.isNull());
            predicate = (StringUtils.isEmpty(suserName)) ? predicate : ExpressionUtils.and(predicate, q.complainUser.like("%" + suserName + "%"));
            predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE));
            predicate = ExpressionUtils.and(predicate, q.status.eq(Constant.MSG_WY));
           /* List<PortalMsgEntity> portalMsgEntities = jpaQueryFactory
                    .selectFrom(q)
                    .where(predicate).fetch();
            String count="0";
            if(portalMsgEntities!=null){
                count=String.valueOf(portalMsgEntities.size());
            }*/
           Long l = jpaQueryFactory.select(q.id.count())
                                   .from(q)
                                   .where(predicate)
                                   .fetchCount();
            if(l!=null){
                return  l.toString();
            }
            return "0";
        }else{
            //用户未登陆时，未获取session返回noSessionMessage用来标识没有用户登陆
            return "noSessionMessage";
        }

    }

}
